import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/app/app_controller.dart';
import 'package:flutter_taotaoshipin/http/dao/drama_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/goods_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/order_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/pay_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/userinfo_dao.dart';
import 'package:flutter_taotaoshipin/model/goods_list_entity.dart';
import 'package:flutter_taotaoshipin/model/pay_config_list_entity.dart';
import 'package:flutter_taotaoshipin/pages/purchase/apple_iap_info.dart';
import 'package:flutter_taotaoshipin/pages/purchase/purchase_type.dart';
import 'package:flutter_taotaoshipin/pages/purchase/view/confirm_open_dialog.dart';
import 'package:flutter_taotaoshipin/util/apple_pay_utils.dart';
import 'package:flutter_taotaoshipin/util/events.dart';
import 'package:flutter_taotaoshipin/value/constant.dart';
import 'package:flutter_taotaoshipin/value/global_config.dart';
import 'package:flutter_taotaoshipin/value/sp_key.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_swiper_null_safety_flutter3/flutter_swiper_null_safety_flutter3.dart';
import 'package:get/get.dart';
import 'package:hi_net/core/hi_error.dart';
import 'package:url_launcher/url_launcher_string.dart';

import 'subscription_open_state.dart';

class SubscriptionOpenController extends GetxController
    with GetSingleTickerProviderStateMixin {
  final SubscriptionOpenState state = SubscriptionOpenState();

  // 轮播图
  late SwiperController swiperController;

  /// 是否已经打开充值页面
  bool _hasOpenPayPage = false;

  /// 订单号
  String _orderId = '';
  String _amount = '';
  int _goodsType = 0;

  /// 订单结果查询次数
  final int _maxCount = 3;
  int _currentCount = 1;

  // 支付结果监听
  StreamSubscription? _subscription;

  @override
  void onInit() {
    super.onInit();
    swiperController = SwiperController();
    if (GlobalConfig.cancelVipType_ios != 0) {
      state.showBack = false;
    }

    // 只受后台控制
    state.isAgreePrivacy =
        GlobalConfig.defaultSelVip_ios == 1 ? true : false;

    // 监听苹果支付结果
    _subscription =
        eventBus.on<ApplePayResult>().listen((event) {
      if (event.status == 'success') {
        UserinfoDao.updateCenter();
        Get.back(result: 1);
      }
    });

    // 获取轮播数据
    _loadBannerData();

    // 获取充值套餐列表
    _loadGoodsListData();
    // 获取充值模板
    _loadPayConfigListData();
  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    swiperController.dispose();
    _subscription?.cancel();
    super.onClose();
  }

  void _loadBannerData() async {
    try {
      var result = await DramaDao.getDramaBanner();
      if (result.code == 0) {
        if (result.data != null) {
          var list = result.data!;
          list.sort((a, b) => a.recSort!.compareTo(b.recSort!));
          state.bannerList = list;
          update(['banner']);
        } else {
          EasyLoading.showToast('数据为空');
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } on HiNetError catch (e) {
      EasyLoading.showToast(e.message);
    } catch (e) {
      EasyLoading.showToast(e.toString());
    }
  }

  /// 充值套餐列表
  Future<void> _loadGoodsListData() async {
    try {
      var result = await GoodsDao.list();
      if (result.code == 0) {
        if (result.data != null) {
          var list = result.data!;
          state.goodsList.clear();
          state.goodsList.addAll(list.where((element) =>
              element.goodsType == PurchaseType.subscription.value));
          state.goodsList.addAll(list.where((element) =>
              element.goodsType == PurchaseType.vip.value));

          if (state.goodsList.isNotEmpty) {
            if (GlobalConfig.pinnerSubIndex >
                state.goodsList.length) {
              state.currGood = state.goodsList.first;
            } else if (GlobalConfig.pinnerSubIndex > 0) {
              state.currGood = state
                  .goodsList[GlobalConfig.pinnerSubIndex - 1];
            }
          }
          update();
        } else {
          EasyLoading.showToast('获取充值套餐列表失败');
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } catch (_) {
      EasyLoading.showToast('网络错误');
    }
  }

  /// 充值模板列表
  Future<PayConfigListEntity?> _loadPayConfigListData() async {
    PayConfigListEntity? entity;
    try {
      var result = await PayDao.configList();
      if (result.code == 0) {
        if (result.data != null) {
          state.payConfigListEntity = result.data!;
          state.currPayConfig = result.data!.list!.first;
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } catch (_) {
      EasyLoading.showToast('网络错误');
    }
    return entity;
  }

  /// 创建订单
  Future<void> _loadOrderCreateData(
    PayConfigListList payConfig,
    GoodsListEntity goodsListEntity,
  ) async {
    try {
      EasyLoading.show(status: '正在下单');
      var result = await OrderDao.create(
        goodsListEntity.amount!,
        goodsListEntity.id!,
        payConfig.code!,
        payConfig.account!,
        payPlatform: payConfig.platform,
      );
      if (result.code == 0) {
        if (result.data != null) {
          EasyLoading.dismiss();
          _orderId = result.data!.orderId!;
          // 数据不为空
          if (payConfig.code == 'apple_pay') {
            var jsonString = Uri.decodeFull(result.data!.payStr!);
            Map<String, dynamic> map = jsonDecode(jsonString);
            var uuid = map['uuid'];
            // 更新全局参数
            var payInfo = InAppPurchaseInfo(
              amount: goodsListEntity.amount,
              orderId: _orderId,
              productId: goodsListEntity.config?.appleGoodsId,
              uuid: uuid,
              payCode: payConfig.code,
            );
            AppController appController = Get.find();
            appController.updateApplePayInfo(payInfo);
            // 发起苹果支付
            await applePayUtils.startApplePay(
                goodsListEntity.config!.appleGoodsId!, uuid);
          } else if (payConfig.code == 'zfb_pay') {
            var url = Uri.decodeFull(result.data!.payStr!);
            _hasOpenPayPage = await launchUrlString(
              url,
              mode: LaunchMode.externalApplication,
            );
          } else if (payConfig.code == 'zfb_app_pay') {
            var url = Uri.decodeFull(result.data!.payStr!);
            _hasOpenPayPage = await launchUrlString(
              url,
              mode: LaunchMode.externalApplication,
            );
          } else {
            // var redirectUrl = Uri.encodeFull(
            // 'https://ts.933you.com/h5/#/pages/rechange/index?order_id=${result.data!.orderId}');
            var redirectUrl = Uri.encodeFull(Constant.urlScheme);
            var url =
                '${result.data!.payReferer}?to_url=${result.data!.payStr}&redirect_url=$redirectUrl';
            _hasOpenPayPage = await launchUrlString(
              url,
              mode: LaunchMode.externalApplication,
            );
          }
        } else {
          EasyLoading.showError('下单失败');
        }
      } else {
        EasyLoading.showError(result.message);
      }
    } catch (e) {
      EasyLoading.showError('网络错误');
    }
  }

  /// 订单状态主动查询
  Future<void> _loadOrderQueryData(String orderId,
      {bool retry = true}) async {
    try {
      EasyLoading.show(status: '订单查询中');
      var result = await OrderDao.query(orderId);
      if (result.code == 0) {
        if (result.data != null) {
          if (result.data!.status == 1) {
            EasyLoading.showSuccess('充值成功');
            // 充值成功，加载用户中心
            await UserinfoDao.updateCenter();
          } else {
            // 充值失败，重试3次
            if (retry) {
              _currentCount++;
              if (_currentCount > _maxCount) {
                _currentCount = 1;
                EasyLoading.showError('充值失败');
                return;
              } else {
                // 延迟1.5秒查询下一次
                Future.delayed(const Duration(milliseconds: 1500), () {
                  _loadOrderQueryData(orderId);
                });
              }
            } else {
              EasyLoading.showError('充值失败');
            }
          }
        } else {
          EasyLoading.showError('数据为空');
        }
      } else {
        EasyLoading.showError(result.message);
      }
    } catch (_) {
      EasyLoading.showError('网络错误');
    }
  }

  void updateCurr(int index) {
    state.currSel = index;
    update(['banner']);
  }

  void agreePrivacyBtnClicked() {
    state.isAgreePrivacy = !state.isAgreePrivacy;
    update(['agreement_button']);
    // 保存状态
    SpUtil.putBool(SpKey.hasMonthTips, true);
  }

  void showPrivateTips() {
    Get.dialog(ConfirmOpenDialog(
      onSuccess: () {
        agreePrivacyBtnClicked();
        toPay();
      },
    ));
  }

  toPay() {
    // 点击之后可返回
    if (!state.showBack) {
      state.showBack = true;
      update(['show_back']);
    }

    if (state.currGood != null &&
        state.currPayConfig != null) {
      _loadOrderCreateData(
          state.currPayConfig!, state.currGood!);
    } else {
      EasyLoading.showToast("当前支付方式不支持");
    }
  }

  void payButtonClicked() {
    if (!state.isAgreePrivacy) {
      showPrivateTips();
      return;
    }
    toPay();
  }
}
